<script setup lang="ts">
import { onMounted, ref } from 'vue';
// 根据项目规则第8条，删除从ant-design-vue引入的message
import { ReloadOutlined } from '@ant-design/icons-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { fetchMarketDataList } from '@/service/api/market-data';

import { useRouterPush } from '@/hooks/common/router';
const { routerPushByKey } = useRouterPush();

// 响应式数据
const loading = ref(false);
const marketDataList = ref<any[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 表格列定义
const columns: TableColumnsType = [
  {
    title: 'ID',
    dataIndex: 'marketId',
    key: 'id',
    width: 120,
    ellipsis: true
  },
  {
    title: '市场数据日期',
    dataIndex: 'horizonDate',
    key: 'horizonDate',
    width: 230
  },
  {
    title: '市场数据类型',
    dataIndex: 'marketDataType',
    key: 'marketDataType',
    width: 150
  },
  {
    title: '数值',
    dataIndex: 'value',
    key: 'value',
    width: 150
  },
  {
    title: '最后更新时间',
    dataIndex: 'lastUpdated',
    key: 'lastUpdated',
    width: 200,
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 200,
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
];

// 获取市场数据列表
async function fetchData() {
  loading.value = true;
  const { data: resData } = await fetchMarketDataList();
  if (resData && Array.isArray(resData)) {
    marketDataList.value = [...resData]; // 使用展开运算符确保触发重新渲染
    pagination.value.total = resData.length;
  } else {
    marketDataList.value = [];
    pagination.value.total = 0;
  }
  loading.value = false;
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
};

// 查看详情
const viewDetail = (record: any) => {
  routerPushByKey('valuation_market-data-detail', {
    query: { id: record.marketId || record.id, view: 'detail' }
  });
};

// 获取类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    INTEREST_RATE: 'blue',
    EXCHANGE_RATE: 'green',
    STOCK_PRICE: 'orange',
    COMMODITY_PRICE: 'purple',
    VOLATILITY: 'red',
    CREDIT_SPREAD: 'cyan'
  };
  return colorMap[type] || 'default';
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return dateStr;
  }
};

// 组件挂载时根据当前视图获取数据
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="market-data-container">
    <ACard title="市场数据管理" :bordered="false">
      <template #extra>
        <ASpace>
          <AButton type="primary" :loading="loading" @click="fetchData">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新数据
          </AButton>
        </ASpace>
      </template>

      <ATable
        :columns="columns"
        :data-source="marketDataList"
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
        }"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <ASpace>
              <AButton type="link" @click="viewDetail(record)">查看详情</AButton>
            </ASpace>
          </template>
          <template v-else-if="column.key === 'marketDataType'">
            <ATag :color="getTypeColor(record.marketDataType)">
              {{ record.marketDataType }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'value'">
            <span v-if="typeof record.value === 'number'">
              {{ record.value.toFixed(6) }}
            </span>
            <span v-else>{{ record.value }}</span>
          </template>
          <template v-else-if="column.key === 'lastUpdated'">
            <span v-if="record.lastUpdated">
              {{ formatDate(record.lastUpdated) }}
            </span>
            <span v-else>-</span>
          </template>
        </template>
      </ATable>
    </ACard>
  </div>
</template>

<style scoped></style>
